package iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.adapter;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.util.ArrayList;
import java.util.List;

import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.R;
import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.activity.secondActivity.ActivityModifyProduct;
import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.entity.Product;
import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.service.IProductService;
import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.service.serviceImpl.ProductService;

public class ProductAdapter extends ArrayAdapter<Product> {
    private static final int REQUEST_CODE_MODIFY = 111;
    private IProductService productService;
    private List<Product> productList; // 数据源

    public ProductAdapter(@NonNull Context context, @NonNull List<Product> products, IProductService productService) {
        super(context, 0, products);
        this.productService = productService; // 通过构造函数传递服务实例
        this.productList = products; // 初始化数据源
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        if (convertView == null) {
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_product_management, parent, false);
        }

        Product product = getItem(position);

        // 获取视图中的控件
        TextView productName = convertView.findViewById(R.id.product_name);
        ImageView productImage = convertView.findViewById(R.id.product_image);
        TextView productDetails = convertView.findViewById(R.id.product_details);
        TextView modifyLink = convertView.findViewById(R.id.modify_link);
        TextView deleteLink = convertView.findViewById(R.id.delete_link);

        // 设置产品名称和生产日期
        productName.setText(product.getProductName());

        // 加载产品图片
        if (product.getImage() != null) {
            Bitmap bitmap = BitmapFactory.decodeByteArray(product.getImage(), 0, product.getImage().length);
            productImage.setImageBitmap(bitmap);
        } else {
            productImage.setImageResource(R.drawable.default_image); // 请替换为您默认的图片资源
        }

        // 设置产品详细信息
        String details = String.format("ID: %s\n分类: %s\n生产日期：%s\n价格: %.2f\n",
                product.getProductId(),
                product.getCategory(),
                product.getProduceDate(),
                product.getPrice());

        // 为产品详情设置点击事件，弹出对话框
        productDetails.setOnClickListener(v -> showProductDetailsDialog(product, details));

        // 设置修改超链接的点击事件
        modifyLink.setOnClickListener(v -> {
            // 创建一个 Intent 跳转到修改产品的活动
            Intent intent = new Intent(getContext(), ActivityModifyProduct.class);
            intent.putExtra("productId", product.getProductId());
            getContext().startActivity(intent);
        });

        deleteLink.setOnClickListener(v -> {
            if (product.getState() > 1){
                Toast.makeText(getContext(), "产品以售卖无法删除", Toast.LENGTH_SHORT).show();
                return;
            }

            // 创建一个确认对话框
            new AlertDialog.Builder(getContext())
                    .setMessage("确定要删除 " + product.getProductName() + " 吗?")
                    .setPositiveButton("确定", (dialog, which) -> {
                        // 用户点击确认，执行删除操作
                        if (productService != null && productService.deleteProduct(product.getProductId())) {
                            Toast.makeText(getContext(), "产品删除成功", Toast.LENGTH_SHORT).show();

                            // 删除成功后从数据源中移除该产品
                            productList.remove(product);  // 从列表中移除被删除的产品

                            // 通知 Adapter 刷新 UI
                            notifyDataSetChanged();
                        } else {
                            Toast.makeText(getContext(), "删除失败", Toast.LENGTH_SHORT).show();
                        }
                    })
                    .setNegativeButton("取消", null)
                    .show();
        });

        return convertView;
    }

    private void showProductDetailsDialog(Product product, String details) {
        // 创建并显示包含产品详细信息的对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setTitle("产品详细信息");
        builder.setMessage(details);
        builder.setPositiveButton("确定", null);
        builder.show();
    }

    // 获取当前 Adapter 中的所有产品列表
    public List<Product> getProductList() {
        return productList;  // 返回当前的产品列表
    }
}


